#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import sys
import string
import json
import MySQLdb
import subprocess
from Tools import connectMySQL
import ConfigParser

#read config                                                                
cf = ConfigParser.ConfigParser()
#cf.read(os.path.dirname(os.path.realpath(__file__))+"../Tools/settings.conf")
cf.read("/opt/wanalytics/Tools/settings.conf")
host = cf.get("MySQL", "host")
user = cf.get("MySQL", "user")
passwd = cf.get("MySQL", "passwd")
#dbMobileProduction = cf.get("MySQL", "dbMobileProduction")
#dbGuid = cf.get("MySQL", "dbGuid")
dbGuid = "tmp_uv"

program_path = "/opt/wanalytics"

def update_lasttime(filename,datetime):
    try:
        db = connectMySQL.connMySQL("tmp_uv")
    except MySQLdb.Error, e:
        print e
    cursor = db.cursor()
    tbname = "client_%s" %(datetime)

    try:
        cursor.execute('''
            create table if not exists `%s` (
            guid char(32) NOT NULL DEFAULT '',
            pid char(16) NOT NULL DEFAULT '',
            lasttime int(10) NOT NULL DEFAULT 0
            );
        ''' %(tbname))
        p = subprocess.Popen("""echo \"load data infile '%s' into table %s fields terminated by ','  optionally enclosed by '\\"' escaped by '\\"' lines terminated by '\\n'\" | mysql -u%s -p%s -h%s %s""" %(filename,tbname,user,passwd,host,dbGuid),shell=True)
        output_stream, error_stream = p.communicate()
#print output_stream
#        print error_stream
#        cursor.execute("alter table tmp_update add index `guid_pid` (`guid`,`pid`)")
#        cursor.execute("update clientUser,tmp_update set clientUser.lasttime=tmp_update.lasttime where clientUser.guid=tmp_update.guid and clientUser.pid=tmp_update.pid");
    except MySQLdb.Error, e:
        raise e
    db.close()

if __name__ == '__main__':
    update_lasttime(sys.argv[1],sys.argv[2]);
